package org.tnc.budget.webapp.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.tnc.budget.service.BudgetManager;
import org.tnc.budget.service.EventManager;
import org.tnc.budget.webapp.util.AuthCryptException;
import org.tnc.budget.webapp.util.BudgetConstants;
import org.tnc.budget.webapp.util.DESHelper;
import org.tnc.model.User;
import org.tnc.service.UserManager;

/**
 * 
 * @author houjj | 2011-4-16 下午06:57:55
 */
@Controller
public class EventDoController implements BudgetConstants{
	
	private EventManager eventManager;
	private UserManager userManager;
	private BudgetManager budgetManager;
	
	private Logger log = Logger.getLogger(EventDoController.class);
	
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	
	public void setEventManager(EventManager eventManager) {
		this.eventManager = eventManager;
	}

	/**
	 * id没有当删除成功
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/delEvents.do")
	public void deleteUserEvent(HttpServletRequest request,
			HttpServletResponse response){
		
		// operation=sych, del
		printRequestParameters(request);
		
		String emailParam = "";
		String authParam = "";
		int result = 0;
		
		User u = null;
		String newPwd = "";
		try {
			emailParam = ServletRequestUtils.getStringParameter(request, "email");
			authParam = ServletRequestUtils.getStringParameter(request, "data");
			if(emailParam == null ){
				throw new ServletRequestBindingException("parameter 'email'");
			}
			
			if(authParam == null)
			{
				throw new ServletRequestBindingException("parameter 'data'");
			}
			
			u = userManager.getUserByUserEmail(emailParam);
			String pwd = u.getPassword();
			newPwd = pwd.substring(SUB_PASSWORD_START_INDEX, SUB_PASSWORD_END_INDEX);
			String ddata = DESHelper.desDecrypt(authParam, newPwd);
			if(log.isDebugEnabled())
				log.debug("Decrypted Data:"+ddata);
			
			String[] eventIds = ddata.split(",");
			
			//	data的数据格式2011/4/17 10:32:11
			if(eventIds == null || eventIds.length < 2 || !isValidData(eventIds[eventIds.length - 1]))
			{
				throw new AuthCryptException("Format of decrypted data error");
			}
			String[] ids = new String[eventIds.length - 1];
			System.arraycopy(eventIds, 0, ids, 0, ids.length);
			
			log.info("del events start, ids length:"+ids.length);
			this.eventManager.saveUnvalidEventTable(u, ids);
				
			result = 1;
			
			log.info("del events successful.");
			
		} catch (ServletRequestBindingException e) {
			log.warn("Parameter 'email' or 'data' not exist, "+e.getMessage());
			result = -4;
		} catch(UsernameNotFoundException e){
			log.warn("User not exist");
			result = -2;
		} catch (AuthCryptException e) {
			log.error("Decrypt Error", e);
			result = -3;
		} catch (Exception e){
			result = -1;
		}
		
		
		
		// 返回结果数据
		PrintWriter out;
		try {
			out = response.getWriter();
			out.println(result);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			log.error("Write reponse message failed when upload file", e);
		}

	}
	
	public static boolean isValidData(String ddata) {
		boolean result = false;
		String[] d = ddata.split("/");
		if(d.length > 2)
		{
			result = true;
		}
		d = ddata.split("-");
		if (d.length > 2) {
			result = true;
		}
		return result;
	}
	
	private void printRequestParameters(HttpServletRequest request) {
		Map params = request.getParameterMap();
		Set s = params.keySet();
		Iterator sit = s.iterator();
		while(sit.hasNext())
		{
			Object o = sit.next();
			String[] v = (String[])params.get(o);
			log.info(o+"="+v[0]);
		}
	}
}
